package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.ArticleInfoDtoV2;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-17
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {


    @Autowired
    private IApBehaviorEntryService entryService;

    @Override
    public void follow(FollowBehaviorDto dto) {

        EntryDto entryDto = new EntryDto();
        entryDto.setUserId(dto.getUserId());
        entryDto.setEquipmentId(dto.getEquipmentId());
        ApBehaviorEntry entry = entryService.getEntry(entryDto);
        // 构建ApFollowBehavior对象
        ApFollowBehavior followBehavior = new ApFollowBehavior();
        if (entry != null) {
            followBehavior.setEntryId(entry.getId());
        }
        followBehavior.setFollowId(dto.getFollowId());
        followBehavior.setOperation(dto.getOperation());
        followBehavior.setCreatedTime(new Date());
        // 判断当前的操作是关注还是取消关注

        // 如果是关注 保存数据 先查询关注记录是否存在
        LambdaQueryWrapper<ApFollowBehavior> query = new LambdaQueryWrapper<>();
        query.eq(ApFollowBehavior::getEntryId, entry.getId());
        query.eq(ApFollowBehavior::getFollowId, dto.getFollowId());
        ApFollowBehavior one = this.getOne(query);
        if (one == null) {
            this.save(followBehavior);
        } else {
            if (dto.getOperation() != one.getOperation()) {
                one.setOperation(dto.getOperation());
                this.updateById(one);
            }
        }
    }

    @Override
    public boolean isFollow(ArticleInfoDtoV2 dto) {
        //判断设备还是用户，可能没必要
        Integer entryId;
        entryId = (dto.getEntryId());
        LambdaQueryWrapper<ApFollowBehavior> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApFollowBehavior::getEntryId,entryId).eq(ApFollowBehavior::getFollowId,dto.getAuthorId());
        ApFollowBehavior followBehavior = getOne(queryWrapper);
        return followBehavior!=null&&followBehavior.getOperation()==0;

    }


}
